import React, { useEffect, useState } from 'react'
import { Select, Tag } from 'antd'
import config from '@/config'
import {
  reqGoodList,
  reqGoodsTypesList,
  type GoodType,
  type Good,
  type GoodResponse,
  reqDeleteGoods,
  reqUpdateGoodState
} from '@/api/good'
import { reqBrandList, type Brand, type ApiResponse } from '@/api/brand'

import {
  Form,
  Input,
  Modal,
  message,
  Table,
  Button,
  type TableProps
} from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import GoodDraw from './GoodDraw'

type TableRowSelection<T extends object = object> =
  TableProps<T>['rowSelection']
type TablePagination<T extends object> = NonNullable<
  Exclude<TableProps<T>['pagination'], boolean>
>
type TablePaginationPosition<T extends object> = NonNullable<
  TablePagination<T>['position']
>[number]
//------------------------------------组件开始的位置
const GoodIndex: React.FC = () => {
  const [form] = Form.useForm()
  const [ids, setIds] = useState<number[]>([])
  const [open, setOpen] = useState<boolean>(false)
  let [id, setId] = useState<number | undefined>()
  const initialValues = {
    bid: '请选择', // 对应 Form.Item 的 name
    gtid: '请选择'
  }
  const [brandList, setBrandList] = useState<Brand[]>()
  const [goodTypeList, setGoodTypeList] = useState<GoodType[]>()
  const [dataSource, SetDataSource] = useState<GoodResponse<Good[]>>()
  const [query, setQuery] = useState({
    pageIndex: 1,
    pageSize: 2,
    gtid: '',
    bid: '',
    info: ''
  })

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [bottom, setBottom] =
    useState<TablePaginationPosition<Good>>('bottomCenter')
  const columns: TableProps<Good>['columns'] = [
    {
      title: '商品编号',
      dataIndex: 'goodsCode'
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName'
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      render: (text) => {
        return <span style={{ color: 'red' }}>￥{text.toFixed(2)}</span>
      }
    },
    {
      title: '商品图片',
      dataIndex: 'photo',
      render: (text) => {
        return (
          <img
            src={config.imgUrl + text}
            alt="商品图片"
            style={{ width: '50px', height: '50px' }}
          />
        )
      }
    },
    {
      title: '商品介绍',
      dataIndex: 'desc',
      render: (text) => {
        return <div dangerouslySetInnerHTML={{ __html: text }} />
      }
    },
    {
      title: '商品状态',
      dataIndex: 'state',
      render: (text) => {
        return (
          <>
            {text === true ? (
              <Tag color="#f50">上架</Tag>
            ) : (
              <Tag color=" #87d068">下架</Tag>
            )}
          </>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, record) => (
        <>
          <Button
            type="primary"
            onClick={() => {
              handleAddGoods(true, record.id, false)
            }}
          >
            编辑
          </Button>
          <Button
            type="primary"
            danger
            onClick={() => {
              handleDelete(record.id)
            }}
          >
            删除
          </Button>
        </>
      )
    }
  ]
  useEffect(() => {
    getBrandList()
    getGoodsTypesList()
    getGoodList()
  }, [query])

  //  useEffect(() => {
  //   getGoodList()
  //   getBrandList()
  //   getGoodsTypesList()
  // }, [])

  //获取品牌列表
  const getBrandList = async () => {
    const res: ApiResponse<Brand[]> = await reqBrandList()

    const list = res.data.map((item) => {
      return {
        value: item.id,
        label: item.bName
      }
    })
    setBrandList(list as unknown as Brand[])
  }
  //获取商品类型列表
  const getGoodsTypesList = async () => {
    const res = await reqGoodsTypesList()

    if (Array.isArray(res.data)) {
      const list = res.data.map((item: GoodType) => {
        return {
          value: item.id,
          label: item.goodsTypeName
        }
      })
      setGoodTypeList(list as unknown as GoodType[])
      console.log(goodTypeList)
    }
  }
  //获取商品列表
  const getGoodList = async () => {
    const res: GoodResponse<Good[]> = await reqGoodList(query)
    console.log(res)
    // 原代码中 good 可能为 undefined，直接展开会有问题，这里直接设置为响应结果
    SetDataSource(res)
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onFinish = (values: any) => {
    console.log('Finish:', values)
  }

  //品牌名称变化时触发的函数
  const handleChangeBname = (value: string) => {
    console.log(`selected ${value}`)
    setQuery({
      ...query,
      bid: value
    })
  }

  //商品类型变化时触发的函数
  const handleChangeGoodType = (value: string) => {
    console.log(`selected ${value}`)
    setQuery({
      ...query,
      gtid: value
    })
  }
  //商品信息变化时触发的函数
  const handleChangeText = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.value)
    setQuery({
      ...query,
      info: e.target.value
    })
  }
  //重置按钮触发的函数
  const handleReset = () => {
    form.resetFields()
    setQuery({
      pageIndex: 1,
      pageSize: 2,
      gtid: '',
      bid: '',
      info: ''
    })
  }

  //确定删除
  const handleOk = async (id: number) => {
    // console.log(JSON.parse(args[0] as string))
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const res: any = await reqDeleteGoods(
      id.toString()
      // JSON.parse(args[0] as string).id.toString()
    )
    console.log(res)
    if (res.data > 0) {
      Modal.success({
        title: '提示',
        content: '删除成功',
        onOk: () => {
          getGoodList()
        }
      })
    }
  }
  //取消操作
  const handleCancel = () => {
    message.warning('点击了取消按钮')
    console.log('点击了取消按钮')
    return
  }

  // 定义删除操作的处理函数
  const handleDelete = async (value: number | undefined) => {
    console.log(`准备删除 ID 为 ${value} 的商品`)
    // 删除成功后可以重新获取商品列表
    Modal.confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '请问确定要删除吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        if (value !== undefined) {
          handleOk(value)
        }
      },
      onCancel: handleCancel
    })
  }

  // 定义批量删除操作的处理函数
  const handleAllOk = async (value: string) => {
    console.log(`准备批量删除 ID 为 ${value} 的商品`)
    // 删除成功后可以重新获取商品列表
    const res: any = await reqDeleteGoods(value)
    console.log(res)
    if (res.data > 0) {
      Modal.success({
        title: '提示',
        content: '删除成功',
        onOk: () => {
          getGoodList()
        }
      })
    }
  }
  //点击批量删除
  const handleDelAll = () => {
    if (ids.length === 0) {
      Modal.warning({
        title: '提示',
        content: '请选择要删除的商品'
      })
      return
    }
    if (ids) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: '请问确定要删除吗?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => handleAllOk(ids.toString()),
        onCancel: handleCancel
      })
    }
  }
  //批量确认上架下架
  const handleUpdateAllOk = async (ids: string, value: boolean) => {
    console.log(`准备批量上架下架 ID 为 ${value} 的商品`)
    const res: any = await reqUpdateGoodState(ids, value)
    console.log(res)
    if (res.data > 0) {
      Modal.success({
        title: '提示',
        content: '修改成功',
        onOk: () => {
          getGoodList()
          // 清除表格的选中状态
          setSelectedRowKeys([])
          setIds([])
        }
      })
    }
  }
  //点击批量上架下架
  const updateAllState = async (value: boolean) => {
    console.log(`准备批量上架下架 ID 为 ${value} 的商品`)
    if (ids.length === 0) {
      Modal.warning({
        title: '提示',
        content: `请选择要${value == true ? '上架' : '下架'}的商品`
      })
      return
    }
    if (ids) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: '请问确定要修改吗?',
        okText: '确认',
        cancelText: '取消',
        onOk: () => handleUpdateAllOk(ids.toString(), value),
        onCancel: handleCancel
      })
    }
  }

  //表格选中状态变化时触发的函数
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys)
    setSelectedRowKeys(newSelectedRowKeys)
    setIds(newSelectedRowKeys as number[])
  }
  //显示复选框
  const rowSelection: TableRowSelection<Good> = {
    selectedRowKeys,
    onChange: onSelectChange
  }
  //点击增加和修改和关闭商品时--------
  const handleAddGoods = (
    isShow: boolean,
    data: number | undefined,
    refreshFlag: boolean
  ) => {
    setOpen(isShow)
    if (data) {
      setId(data)
    } else {
      setId(0)
    }
    if (refreshFlag) {
      getGoodList()
      setId(data)
    }
  }

  //---------------------视图-----------------------------------//
  return (
    <div>
      <h3>商品页面</h3>
      {/* 操作按钮 */}
      <div style={{ marginBottom: 10 }}>
        <Button
          type="primary"
          onClick={() => {
            handleAddGoods(true, undefined, false)
          }}
        >
          增加
        </Button>
        <Button type="primary" danger onClick={handleDelAll}>
          {' '}
          批量删除
        </Button>
        <Button type="default" onClick={() => updateAllState(true)}>
          批量上架
        </Button>
        <Button type="default" onClick={() => updateAllState(false)}>
          批量下架
        </Button>
      </div>
      {/* 查询条件 */}
      <Form
        form={form}
        name="horizontal_login"
        initialValues={initialValues}
        layout="inline"
        onFinish={onFinish}
      >
        <Form.Item label="商品信息" name="info">
          <Input placeholder="请输入商品信息" onChange={handleChangeText} />
        </Form.Item>
        <Form.Item label="品牌名称" name="bid">
          {/* initialValues="请选择" */}
          <Select
            options={brandList}
            onChange={handleChangeBname}
            style={{ width: 100 }}
          />
        </Form.Item>
        <Form.Item label="商品类型" name="gtid">
          {/* initialValues="请选择" */}
          <Select
            options={goodTypeList}
            onChange={handleChangeGoodType}
            style={{ width: 100 }}
          />
        </Form.Item>
        <Form.Item shouldUpdate>
          {() => (
            <div>
              <Button type="primary" onClick={() => getGoodList()}>
                查询
              </Button>
              <Button type="default" onClick={handleReset}>
                重置
              </Button>
            </div>
          )}
        </Form.Item>
      </Form>
      {/* 表格 */}

      <Table<Good>
        bordered={true}
        // 为了避免 record.id 可能为 undefined 的问题，这里使用空值合并运算符确保返回值不为 undefined
        rowKey={(record) => record.id ?? -1}
        dataSource={dataSource?.data.data || []}
        columns={columns}
        rowSelection={rowSelection}
        pagination={{
          current: query.pageIndex,
          onChange: (pageIndex: number, pageSize: number) => {
            setQuery({
              ...query!,
              pageIndex: pageIndex,
              pageSize: pageSize
            })
            // getGoodList()
          },
          defaultCurrent: 1,
          defaultPageSize: query.pageSize,
          total: dataSource?.data.totalCount || 0,
          pageSizeOptions: [2, 3, 4, 5, 6],
          showSizeChanger: true,
          showQuickJumper: true,
          position: ['bottomCenter'],
          showTotal: (total: number, range: [number, number]) => {
            return `共${total}条数据，当前显示${range[0]}-${range[1]}条`
          }
        }}
      />

      {/* 抽屉 */}
      <GoodDraw id={id} open={open} onClose={handleAddGoods} />
    </div>
  )
}

export default GoodIndex
